﻿using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections.Specialized;

 
    public class IniHelper
    {
        public string IniFilePath;

        //构造函数
        public IniHelper(string FilePath)
        {
            IniFilePath = FilePath;
            // 判断文件是否存在  
            FileInfo fileInfo = new FileInfo(FilePath);
            //Todo:搞清枚举的用法  
            if ((!fileInfo.Exists))
            { //|| (FileAttributes.Directory in fileInfo.Attributes))  
                //文件不存在，建立文件  
                System.IO.StreamWriter sw = new System.IO.StreamWriter(FilePath, false, System.Text.Encoding.Default);
                try
                {
                    sw.Write("#表格配置档案");
                    sw.Close();
                }
                catch
                {
                    throw (new ApplicationException("Ini文件不存在"));
                }
            }
            //必须是完全路径，不能是相对路径  
            IniFilePath = fileInfo.FullName;
        }



        #region API函数声明

        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);


        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
           string def, StringBuilder retVal, int size, string filePath);

        //声明读写INI文件的API函数  

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);

        #endregion






        #region 读Ini文件

        public string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }
        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="Key"></param>
        /// <param name="NoText">值为空时，显示的文本</param>
        /// <returns></returns>
        public string ReadIniData(string Section, string Key, string NoText)
        {
            return ReadIniData(Section, Key, NoText, this.IniFilePath);
        }
        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public string ReadIniData(string Section, string Key)
        {
            return ReadIniData(Section, Key, "空", this.IniFilePath);
        }

        //从Ini文件中，读取所有的Sections的名称  
        public void ReadSections(StringCollection SectionList)
        {
            //Note:必须得用Bytes来实现，StringBuilder只能取到第一个Section  
            byte[] Buffer = new byte[65535];
            int bufLen = 0;
            bufLen = GetPrivateProfileString(null, null, null, Buffer, Buffer.GetUpperBound(0), IniFilePath);
            GetStringsFromBuffer(Buffer, bufLen, SectionList);
        }

        //读取指定的Section的所有Value到列表中  
        public void ReadSectionValues(string Section, NameValueCollection Values)
        {
            StringCollection KeyList = new StringCollection();
            ReadSection(Section, KeyList);
            Values.Clear();
            foreach (string key in KeyList)
            {
                Values.Add(key, ReadIniData(Section, key, ""));
            }
        }






        #endregion

        #region 写Ini文件

        public   bool WriteIniData(string Section, string Key, string Value,string FileName )
        {
            if (File.Exists(FileName))
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, FileName);
                if (OpStation == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }

        #endregion



        #region  清除 与 删除
        //清除某个Section  
        public void ClearSection(string Section)
        {
            if (WritePrivateProfileString(Section, null, null, IniFilePath) < 0)
            {
                throw (new ApplicationException("无法清除Ini文件中的Section"));
            }
        }

        //删除某个Section下的键  
        public void DeleteKey(string Section, string Ident)
        {
            WritePrivateProfileString(Section, Ident, null, IniFilePath);
        }



        #endregion

        //检查某个Section下的某个键值是否存在  
        public bool ValueExists(string Section, string Ident)
        {
            StringCollection Idents = new StringCollection();
            ReadSection(Section, Idents);
            return Idents.IndexOf(Ident) > -1;
        }

        #region 确保资源释放
        //Note:对于Win9X，来说需要实现UpdateFile方法将缓冲中的数据写入文件  
        //在Win NT, 2000和XP上，都是直接写文件，没有缓冲，所以，无须实现UpdateFile  
        //执行完对Ini文件的修改之后，应该调用本方法更新缓冲区。  
        public void UpdateFile()
        {
            WritePrivateProfileString(null, null, null, IniFilePath);
        }



        //确保资源的释放  
        ~IniHelper()
        {
            UpdateFile();
        }

        #endregion




        //从Ini文件中，将指定的Section名称中的所有Ident添加到列表中  
        public void ReadSection(string Section, StringCollection Idents)
        {
            Byte[] Buffer = new Byte[16384];
            //Idents.Clear();  

            int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0), IniFilePath);
            //对Section进行解析  
            GetStringsFromBuffer(Buffer, bufLen, Idents);
        }


        private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
        {
            Strings.Clear();
            if (bufLen != 0)
            {
                int start = 0;
                for (int i = 0; i < bufLen; i++)
                {
                    if ((Buffer[i] == 0) && ((i - start) > 0))
                    {
                        String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);
                        Strings.Add(s);
                        start = i + 1;
                    }
                }
            }
        }







    }
 